package com.zyh.langchain4j.repository;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;

@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取会话消息
     *
     * @param memoryId
     * @return
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        // 1.redis获取数据
        String json = (String) redisTemplate.opsForValue().get(memoryId.toString());
        // 2.json转list
        return ChatMessageDeserializer.messagesFromJson(json);
    }

    /**
     * 更新会话消息
     *
     * @param memoryId
     * @param list
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        // 1.list转json
        String json = ChatMessageSerializer.messagesToJson(list);
        // 2.保存到redis中,1天
        redisTemplate.opsForValue().set(memoryId.toString(), json, Duration.ofDays(1));
    }

    /**
     * 删除会话消息
     *
     * @param memoryId
     */
    @Override
    public void deleteMessages(Object memoryId) {
        redisTemplate.delete(memoryId.toString());
    }
}
